package com.ruicar.afs.cloud.afscase.approvetask.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.approvemakelabel.entity.ApproveMakeLabel;
import com.ruicar.afs.cloud.afscase.approvemakelabel.service.ApproveMakeLabelService;
import com.ruicar.afs.cloud.afscase.approveprev.entity.CaseApprovePrevInfo;
import com.ruicar.afs.cloud.afscase.approveprev.service.CaseApprovePrevInfoService;
import com.ruicar.afs.cloud.afscase.approvetask.condition.WorkTaskPoolCondition;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolService;
import com.ruicar.afs.cloud.afscase.approvetask.vo.CaseBaseInfoVo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelRiskInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelRiskInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCarInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseChannelInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCarInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseChannelInfoService;
import com.ruicar.afs.cloud.afscase.remind.entity.CaseRemindDetail;
import com.ruicar.afs.cloud.afscase.remind.service.RemindService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessStateInEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.LabelPositionEnum;
import com.ruicar.afs.cloud.parameter.commom.service.TsysAddressParamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jiaqi.guo
 * @version 1.0
 * @description:案件查询
 * @created 2020/5/27 14:31
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("案件")
@RequestMapping("/approve")
public class CaseInfoTaskController {

    private WorkTaskPoolService workTaskPoolService;

    private CaseCarInfoService caseCarInfoService;

    private ApproveMakeLabelService approveMakeLabelService;

    private CaseChannelInfoService caseChannelInfoService;

    private ChannelBaseInfoService channelBaseInfoService;

    private ChannelRiskInfoService channelRiskInfoService;

    private TsysAddressParamService tsysAddressParamService;

    private RemindService remindService;

    private CaseApprovePrevInfoService caseApprovePrevInfoService;


    @PostMapping(value = "/queryCaseInfoTaskList")
    @ApiOperation(value = "多条件分页获取案件信息")
    public IResponse<IPage<CaseBaseInfoVo>> queryCaseInfoTaskList(@ModelAttribute WorkTaskPoolCondition condition) {
        if(CollectionUtil.isNotEmpty(condition.getApplyNoSet())){
            condition.setApplyNoSet(new HashSet<>(condition.getApplyNoSet()));
        }else{
            condition.setApplyNoSet(null);
        }
        //获取标签Id
        String[] str = condition.getTag();
        List labelIdList = new ArrayList();
        if (str!=null&&str.length>0) {
            for (int i = 0; i < str.length; i++) {
                labelIdList.add(str[i]);
            }
        }
        if (labelIdList != null && labelIdList.size() > 0) {
            condition.setLabelList(labelIdList);
        }
        IPage<CaseBaseInfoVo> pageResult = workTaskPoolService.queryCaseInfoTaskList(
                new Page(condition.getPageNumber(), condition.getPageSize()),
                condition);
        List<String> appplyNoList= new ArrayList<>();
        pageResult.getRecords().forEach(caseBaseInfoVo -> {
            appplyNoList.add(caseBaseInfoVo.getApplyNo());

        });
        if(CollectionUtil.isNotEmpty(appplyNoList)){
            pageResult= getCaseBaseInfoLsit(appplyNoList, pageResult);

        }
        return IResponse.success(pageResult);

    }
    /**
     * @description:组装数据
     * @author jiaqi.guo
     * @created 2020/9/22 13:57
     * @version 1.0
     */
    public  IPage<CaseBaseInfoVo>  getCaseBaseInfoLsit(List<String> applyNoList,IPage<CaseBaseInfoVo> pageResult ){

        Map<String,CaseCarInfo> caseCarInfoMap=caseCarInfoService.list(Wrappers.<CaseCarInfo>query().lambda()
                .in(CaseCarInfo::getApplyNo, applyNoList)).stream().collect(Collectors.toMap(CaseCarInfo::getApplyNo, caseCarInfo -> caseCarInfo));

        Map<String,CaseChannelInfo> caseChannelInfoMap = caseChannelInfoService.list(Wrappers.<CaseChannelInfo>query().lambda()
                .in(CaseChannelInfo::getApplyNo, applyNoList)).stream().collect(Collectors.toMap(CaseChannelInfo::getApplyNo, caseChannelInfo -> caseChannelInfo));

        Map<String,CaseApprovePrevInfo> approvePrevInfoMap = caseApprovePrevInfoService.list(Wrappers.<CaseApprovePrevInfo>lambdaQuery()
                .in(CaseApprovePrevInfo::getApplyNo, applyNoList)).stream().collect(Collectors.toMap(CaseApprovePrevInfo::getApplyNo, approvePrevInfo -> approvePrevInfo));



        for(int i=0;  i< applyNoList.size();i++){
            pageResult.getRecords().get(i).setCarName(caseCarInfoMap.get(applyNoList.get(i))!=null?caseCarInfoMap.get(applyNoList.get(i)).getModelName():null);
           /* pageResult.getRecords().get(i).setDealerName(caseChannelInfoMap.get(applyNoList.get(i))!=null?caseChannelInfoMap.get(applyNoList.get(i)).getDealerName():null);*/
            pageResult.getRecords().get(i).setRefuseReason(approvePrevInfoMap.get(applyNoList.get(i))!=null?approvePrevInfoMap.get(applyNoList.get(i)).getRefuseReason():null);

            ChannelBaseInfo channelInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda()
                    .eq(ChannelBaseInfo::getChannelCode, caseChannelInfoMap.get(applyNoList.get(i)).getDealerNo())
            );
            /**---------------------------------   渠道风控信息    --------------------------------**/
            if (ObjectUtils.isNotEmpty(channelInfo)) {
                /**城市*/
                String city = tsysAddressParamService.getProvinceOrCtiy(channelInfo.getChannelCity()) != null ? tsysAddressParamService.getProvinceOrCtiy(channelInfo.getChannelCity()).getLabel() : "";
                pageResult.getRecords().get(i).setChannelCity(city);
                ChannelRiskInfo channelRiskInfo = channelRiskInfoService.getOne(Wrappers.<ChannelRiskInfo>query().lambda()
                        .eq(ChannelRiskInfo::getChannelId, channelInfo.getChannelId().toString())
                        .eq(ChannelRiskInfo::getBusinessType, pageResult.getRecords().get(i).getBusinessType()));
                if (ObjectUtils.isNotEmpty(channelRiskInfo)) {
                    /**合作商评级*/
                    pageResult.getRecords().get(i).setChannelGrade(channelRiskInfo.getChannelGrade());
                }
            }

           /* *  标签信息 **/
            List<ApproveMakeLabel> labelList = approveMakeLabelService.list(Wrappers.<ApproveMakeLabel>query().lambda()
                    .eq(ApproveMakeLabel::getApplyNo, applyNoList.get(i))
                    .eq(ApproveMakeLabel::getLabelLocation, LabelPositionEnum.LIST.getCode()));
            pageResult.getRecords().get(i).setLabelList(labelList);
            if(AfsEnumUtil.key(BusinessStateInEnum.PAUSE).equals(pageResult.getRecords().get(i).getBusinessStateIn())) {
                // 暂停原因
                Optional<CaseRemindDetail> remindDetailOptional = remindService.queryNewestRemindOpt(pageResult.getRecords().get(i).getApplyNo());
                if (remindDetailOptional.isPresent()) {
                    pageResult.getRecords().get(i).setParseMessage(remindDetailOptional.get().getRemindContent());
                }
            }
        }
       return  pageResult;
    }

}
